import numpy as np
import matplotlib.pyplot as plt
import struct

#y(n) = (x(n)+x(n-1)+x(n-2)+x(n-3)+...)/100
class Digitfilter:
    def __init__(self):
        self.xn = [0]*10
        print(self.xn)
        pass
    
    def filter(self,x):
        y = x
        self.xn[0] = x
        for i in range(9,0,-1):
            y = y + self.xn[i]
            self.xn[i] = self.xn[i-1]
        return y/10


if __name__ =='__main__':

    fp = open("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102.dat","rb")
    fp_out = open("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102_out.dat","wb")
    diff = Digitfilter()
    for i in range(0,2500):
        x = struct.unpack('h',fp.read(2))
        y = diff.filter(x[0])
        fp_out.write(struct.pack('h',int(y)))
    fp.close()#close() 函数是专门用来关闭已打开文件的
    fp_out.close()

    ecg0 = np.fromfile("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102.dat",dtype=np.short)
    ecg1 = np.fromfile("D:/wuhui/testcode/SmartHealth-master/DATA/mitdb/102_out.dat",dtype=np.short)
    plt.subplot(2,1,1)
    plt.plot(ecg0[0:500])
    plt.subplot(2,1,2)
    plt.plot(ecg1[0:500])
    plt.show()